<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input :placeholder="'姓名'" v-model="listQuery.name" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>
      <el-select v-model="listQuery.sex" :placeholder="'性别'" clearable style="width: 120px" class="filter-item">
        <el-option :label="'男'" :value="0"/>
        <el-option :label="'女'" :value="1"/>
      </el-select>
      <el-select v-model="listQuery.education" :placeholder="'学历'" clearable style="width: 120px" class="filter-item">
        <el-option label="不限" value="不限"/>
        <el-option label="大专" value="大专"/>
        <el-option label="本科" value="本科"/>
        <el-option label="硕士/研究生" value="硕士/研究生"/>
        <el-option label="博士/研究生" value="博士/研究生"/>
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">{{ $t('table.search') }}</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">{{ $t('table.add') }}</el-button>
      <el-button v-if="list" :disabled="list.length===0" class="filter-item" icon="el-icon-download" type="success" @click="exportExcel">导出</el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
      @selection-change="handleSelectionChange">
      <!--<el-table-column :label="'序号'" prop="id" align="center" width="65">-->
      <!--<template slot-scope="scope">-->
      <!--<span>{{ scope.row.id }}</span>-->
      <!--</template>-->
      <!--</el-table-column>-->
      <el-table-column :label="'姓名'" width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'推荐职位'">
        <template slot-scope="scope">
          <span>{{ scope.row.recommend }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'初次推荐'" width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.first_recommend }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="showReviewer" :label="'最近推荐'" width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.first_recommend }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'性别'" width="80px">
        <template slot-scope="scope">
          <span>{{ scope.row.sex_name }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'出生日期'" align="center" width="95">
        <template slot-scope="scope">
          <span>{{ scope.row.birthday }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'学历'" class-name="status-col" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.education }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'学校'" class-name="status-col" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.university }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'专业'" class-name="status-col" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.profession }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'面试状态'" class-name="status-col" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.interview_status_name }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'完整简历'" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <a v-if="scope.row.resume" :href="scope.row.resume" target="_blank"><el-button type="text">预览简历</el-button></a>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" layout="total, prev, pager, next" @pagination="getList" />

    <el-dialog :title="dialogStatus === 'create' ? '新建人才' : '编辑人才'" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="90px" style="width: 400px; margin-left:50px;">
        <el-form-item :label="'姓名：'">
          <el-input v-model="temp.name"/>
        </el-form-item>
        <el-form-item :label="'推荐职位：'">
          <el-input v-model="temp.recommend"/>
        </el-form-item>
        <el-form-item :label="'初次推荐：'">
          <el-input v-model="temp.first_recommend"/>
        </el-form-item>
        <el-form-item :label="'性别：'">
          <el-radio-group v-model="temp.sex">
            <el-radio :label="0">男</el-radio>
            <el-radio :label="1">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="'出生日期：'">
          <el-date-picker
            v-model="temp.birthday"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item :label="'学历：'">
          <el-select v-model="temp.education" class="filter-item">
            <el-option :label="'大专'" :value="'大专'"/>
            <el-option :label="'本科'" :value="'本科'"/>
            <el-option :label="'硕士'" :value="'硕士'"/>
            <el-option :label="'博士'" :value="'博士'"/>
          </el-select>
        </el-form-item>
        <el-form-item :label="'学校：'">
          <el-input v-model="temp.university"/>
        </el-form-item>
        <el-form-item :label="'专业：'">
          <el-input v-model="temp.profession"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">{{ $t('table.confirm') }}</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel"/>
        <el-table-column prop="pv" label="Pv"/>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">{{ $t('table.confirm') }}</el-button>
      </span>
    </el-dialog>

    <el-dialog :visible.sync="waitDialogVisible" width="30%" title="待面试-面试批次">
      <el-form ref="waitForm" :model="waitForm" label-width="80px">
        <el-form-item label="面试时间">
          <el-date-picker v-model="waitForm.time" type="datetime" placeholder="请选择面试时间" value-format="timestamp">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="面试组别">
          <el-select v-model="waitForm.group" clearable placeholder="请选择组别">
            <el-option label="A" value="A"></el-option>
            <el-option label="B" value="B"></el-option>
            <el-option label="C" value="C"></el-option>
            <el-option label="D" value="D"></el-option>
            <el-option label="E" value="E"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="waitDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="waitCreateData">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog :visible.sync="secondDialogVisible" width="30%" title="二面-面试批次">
      <el-form ref="secondForm" :model="secondForm" label-width="80px">
        <el-form-item label="面试批次">
          <el-date-picker v-model="secondForm.time" type="datetime" placeholder="请选择面试时间" value-format="timestamp">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="面试组别">
          <el-select v-model="secondForm.group" clearable placeholder="请选择组别">
            <el-option label="A" value="A"></el-option>
            <el-option label="B" value="B"></el-option>
            <el-option label="C" value="C"></el-option>
            <el-option label="D" value="D"></el-option>
            <el-option label="E" value="E"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="secondDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="secondCreateData">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { fetchPv } from '@/api/article'
import { getToken } from '@/utils/auth'
import { getTalentSpecialList, createTalent, updateTalent, deleteTalent, sendWaiting, mulWaiting, sendSecond } from '@/api/talent'
import { exportTalentSpecialList } from '@/api/export'
import waves from '@/directive/waves' // Waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj ,such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'FirstNotCome',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        name: '',
        sex: undefined,
        interview_status: undefined,
        education: ''
      },
      queryString: '',
      multUploadUrl: `${process.env.BASE_API}/api/talent/upload`,
      uploadResumeUrl: `${process.env.BASE_API}/api/talent/upload_resume`,
      uploadHeaders: { Authorization: `Bearer ${getToken()}` },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        id: undefined,
        name: '',
        recommend: '',
        first_recommend: '',
        sex: 0,
        birthday: undefined,
        education: '',
        university: '',
        profession: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      dialogPvVisible: false,
      waitDialogVisible: false,
      secondDialogVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false,
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      mulIds: undefined,
      waitForm: {
        id: undefined,
        time: undefined,
        group: undefined
      },
      secondForm: {
        id: undefined,
        time: undefined,
        group: undefined
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      getTalentSpecialList(this.listQuery.page, { interview_status: 4 }, this.queryString).then(response => {
        this.list = response.data.data
        this.total = response.data.meta.pagination.total
        this.listQuery.page = response.data.meta.pagination.current_page++
      }).catch(err => {
        console.log(err)
      }).finally(() => {
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      let query = ''
      const name = this.listQuery.name
      const sex = this.listQuery.sex
      const interview_status = this.listQuery.interview_status
      const education = this.listQuery.education
      if (name) {
        query += `name=${name}&`
      }
      if (sex || sex === 0) {
        query += `sex=${sex}&`
      }
      if (interview_status || interview_status === 0) {
        query += `interview_status=${interview_status}&`
      }
      if (education) {
        query += `education=${education}&`
      }
      this.queryString = query
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        name: '',
        recommend: '',
        first_recommend: '',
        sex: 0,
        birthday: undefined,
        education: '',
        university: '',
        profession: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createTalent(this.temp).then(response => {
            this.list.push(response.data)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateTalent(tempData).then(() => {
            for (const v of this.list) {
              if (v.id === this.temp.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.temp)
                break
              }
            }
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row) {
      const id = row.id
      this.$confirm('此操作将永久删除该信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteTalent(id).then(response => {
          console.log(response)
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          const index = this.list.indexOf(row)
          this.list.splice(index, 1)
        })
      }).catch(() => {})
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    uploadHandleRemove(file, fileList) {
      console.log(file, fileList)
    },
    uploadHandlePreview(file) {
      console.log(file)
    },
    uploadHandleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    uploadBeforeRemove(file, fileList) {
      return this.$confirm(`确定移除${file.name}？`)
    },
    handleInterview(type, id) {
      switch (type) {
        case 'wait':
          this.waitDialogVisible = true
          this.waitForm.id = id
          break
        case 'second':
          this.secondDialogVisible = true
          this.secondForm.id = id
          break
      }
    },
    waitCreateData() {
      const id = this.waitForm.id
      const time = this.waitForm.time / 1000
      const group = this.waitForm.group
      sendWaiting(id, time, group).then(response => {
        this.waitDialogVisible = false
        for (const v of this.list) {
          if (v.id === response.data.id) {
            const index = this.list.indexOf(v)
            this.list.splice(index, 1, response.data)
            break
          }
        }
        this.$message({
          message: '操作成功',
          type: 'success'
        })
      }).catch(err => {
        console.log(err)
      })
    },
    secondCreateData() {
      const id = this.secondForm.id
      const time = this.secondForm.time / 1000
      const group = this.secondForm.group
      sendSecond(id, time, group).then(response => {
        this.secondDialogVisible = false
        for (const v of this.list) {
          if (v.id === response.data.id) {
            const index = this.list.indexOf(v)
            this.list.splice(index, 1, response.data)
            break
          }
        }
        this.$message({
          message: '操作成功',
          type: 'success'
        })
      }).catch(err => {
        console.log(err)
      })
    },
    handleSelectionChange(val) {
      const a = []
      val.forEach(item => {
        a.push(item.id)
      })
      this.mulIds = a
      console.log(this.mulIds)
    },
    mulWaiting() {
      const data = { ids: this.mulIds }
      mulWaiting(data).then(response => {
        this.$message({
          message: '操作成功',
          type: 'success'
        })
      }).catch(err => {
        console.log(err)
      }).finally(() => {
        this.getList()
      })
    },
    showWaitButton(status) {
      return status === 0
    },
    showSecondButton(status) {
      return status === 5
    },
    uploadData(id) {
      const obj = {}
      obj.id = id
      return obj
    },
    uploadSuccess() {
      this.getList()
    },
    exportExcel() {
      exportTalentSpecialList(4, this.listQuery).then(response => {
        window.location.href = response.data.url
      })
    }
  }
}
</script>

<style scoped>
  .success {
    color: #67C23A;
  }
</style>
